/*

    This file is part of Hometree.

    Hometree is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Hometree is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Hometree.  If not, see <http://www.gnu.org/licenses/>.

    Copyright 2011,2012 Roman Held

*/
#include <QDebug>
#include <iostream>
#include "monitor.h"

Monitor::Monitor()
{
  connect(&mClient, SIGNAL(stateChanged()),
          this, SLOT(clientState()));
  connect(&mClient, SIGNAL(urlIdent(const QString &, qint32, qint32)),
          this, SLOT(newUrlIdent(const QString &, qint32, qint32)));
  connect(&mClient, SIGNAL(resourceMsg(qint32, QDataStream &)),
          this, SLOT(newResourceMsg(qint32, QDataStream &)));
  connect(&mClient, SIGNAL(monitorMsg(QDataStream &)),
          this, SLOT(monitorMsg(QDataStream &)));

  mClient.setAutoConnect(true);
  mClient.connectToHost("127.0.0.1",7000);
}

void Monitor::clientState()
{
  std::cout << "New Client state (" << mClient.isReady() << ")" << std::endl;
  if (mClient.isReady())
    init();
}

void Monitor::init()
{
  Q_ASSERT(mClient.isReady());
  mClient.prepareStream(Htr::Net::ClMonitorMsg);
  mClient.writeStream(); 
}

void Monitor::newUrlIdent(const QString &url, qint32 ident, qint32)
{
  mUrlIdents.insert(ident,url);
  std::cout << "Created: " << url.toAscii().data() << std::endl;
}

void Monitor::newResourceMsg(qint32 ident, QDataStream &msg)
{
  qint32 msgType;
  msg >> msgType;
  switch(msgType) {
    case Htr::Net::EventMsg: handleEventMsg(ident, msg); break;
  }
}

void Monitor::monitorMsg(QDataStream &msg)
{
  qint32 ident;
  qint32 msgType;
  msg >> ident;
  msg >> msgType;
  switch (msgType) {
    case Htr::Net::EventMsg: {
      handleEventMsg(ident, msg); 
    } break;
  }
}

void Monitor::handleEventMsg(qint32 ident, QDataStream &msg)
{
  qint32 eventType;
  msg >> eventType;
  switch (eventType) {
    case Htr::Net::EvChanged: {
      std::cout << "Changed: " << mUrlIdents[ident].toAscii().data() << std::endl;
    } break;
    case Htr::Net::EvRemoved: {
      std::cout << "Removed: " << mUrlIdents[ident].toAscii().data() << std::endl;
    } break;
  }  
}

